package com.jxc.action.kcgl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;

import com.jxc.action.BaseAction;
import com.jxc.model.vo.DataGrid;
import com.jxc.model.vo.Json;
import com.jxc.model.vo.SessionInfo;
import com.jxc.model.vo.VBrand;
import com.jxc.model.vo.VChecklist;
import com.jxc.model.vo.VChecklistItem;
import com.jxc.model.vo.VGoods;
import com.jxc.model.vo.VGoodsRepertory;
import com.jxc.model.vo.VRepertory;
import com.jxc.model.vo.VUser;
import com.jxc.service.ChecklistItemServiceI;
import com.jxc.service.ChecklistServiceI;
import com.jxc.service.GoodsRepertoryServiceI;
import com.jxc.service.GoodsServiceI;
import com.jxc.service.RepertoryServiceI;
import com.jxc.service.UserServiceI;
import com.jxc.util.ExceptionUtil;
import com.jxc.util.ResourceUtil;
import com.opensymphony.xwork2.ModelDriven;

@Namespace("/kcgl")
@Action(value = "goodsCheckAction", results = { @Result(name = "goodsCheck", location = "/amountRelate/goodsCheck.jsp") })
public class GoodsCheckAction extends BaseAction implements ModelDriven<VChecklist> {
	private final static Logger logger = Logger.getLogger(GoodsCheckAction.class);
	private VChecklist model = new VChecklist();
	private String items;

	@Autowired
	private ChecklistServiceI checklistService;
	@Autowired
	private ChecklistItemServiceI checklistItemService;
	@Autowired
	private UserServiceI userService;
	@Autowired
	private RepertoryServiceI repertoryService;
	@Autowired
	private GoodsServiceI goodsService;
	@Autowired
	private GoodsRepertoryServiceI goodsreService;

	public String goodsCheck() {
		getSubAuths("KCGL_KCPD");
		return "goodsCheck";
	}

	public String goodsCheckItem() {
		return "goodsCheckItem";
	}

	public void datagrid() throws Exception {
		if (model.getBeginDate() != null) {
			String beginDateStr = new SimpleDateFormat("yyyy-MM-dd").format(model.getBeginDate());
			model.setBeginDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(beginDateStr + " 00:00:00"));
		}
		if (model.getEndDate() != null) {
			String endDateStr = new SimpleDateFormat("yyyy-MM-dd").format(model.getEndDate());
			model.setEndDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endDateStr + " 23:59:59"));
		}

		if (model.getRid() != null) {
			this.writeJson(checklistService.datagrid(model));
		} else {
			SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
			VUser vuser = userService.get(sessionInfo.getUserId());
			if (vuser.getReid() != null) {
				model.setRid(vuser.getReid());
				this.writeJson(checklistService.datagrid(model));
			} else {
				VRepertory vrepertory = new VRepertory();
				vrepertory.setUid(sessionInfo.getUserId());
				List<VRepertory> vrepertories = repertoryService.list(vrepertory);
				if (vrepertories != null && vrepertories.size() > 0) {
					List<VBrand> rows = new ArrayList<VBrand>();
					Long total = 0l;
					for (VRepertory vre : vrepertories) {
						model.setRid(vre.getId());
						DataGrid subDg = checklistService.datagrid(model);
						rows.addAll(subDg.getRows());
						total += subDg.getTotal();
					}
					DataGrid totalDg = new DataGrid();
					totalDg.setRows(rows);
					totalDg.setTotal(total);
					this.writeJson(totalDg);
				} else {
					DataGrid dg = new DataGrid();
					dg.setTotal(0l);
					dg.setRows(new ArrayList<VBrand>());
					this.writeJson(dg);
				}
			}
		}
	}

	/**
	 * 生成盘点单
	 */
	public void add() {
		Json j = new Json();
		try {
			j.setMsg("添加成功！");
			j.setSuccess(true);
		} catch (Exception e) {
			j.setMsg("添加失败！");
			logger.info(ExceptionUtil.getExceptionMessage(e));
		}
		super.writeJson(j);
	}

	/**
	 * 修改盘点单
	 * 
	 */
	public void edit() {
		Json j = new Json();
		try {
			/*
			 * ----------------------------------------------------------------------
			 * 查询盘点单
			 * ----------------------------------------------------------------------
			 */
			List<VChecklist> cls = checklistService.combobox(model);
			VChecklist vcl = cls.get(0);

			/*
			 * ----------------------------------------------------------------------
			 * 将盘点结果保存到盘点明细中
			 * ----------------------------------------------------------------------
			 */
			String[] itemStrs = items.split(",");
			for (int i = 0; i < itemStrs.length; i++) {
				String id = itemStrs[i];
				String checkAmount = itemStrs[++i];
				String checkDate = itemStrs[++i];

				VChecklistItem param = new VChecklistItem();
				param.setId(Long.parseLong(id));
				List<VChecklistItem> vclis = checklistItemService.combobox(param);
				VChecklistItem vcli = vclis.get(0);
				vcli.setIsChecked(true);
				vcli.setCheckAmount(Long.parseLong(checkAmount));
				vcli.setCheckDate(new SimpleDateFormat("yyyy-MM-dd").parse(checkDate));
				checklistItemService.update(vcli);
			}

			/*
			 * ----------------------------------------------------------------------
			 * 查询所有盘点明细，判断是否所有的盘点明细都有盘点时间，是则表明盘点完成，
			 * ----------------------------------------------------------------------
			 */
			VChecklistItem param = new VChecklistItem();
			param.setClid(model.getId());
			List<VChecklistItem> vclis = checklistItemService.combobox(param);
			boolean checkedOver = true;
			for (VChecklistItem vcli : vclis) {
				if (!vcli.getIsChecked()) {
					checkedOver = false;
					break;
				}
			}

			/*
			 * ----------------------------------------------------------------------
			 * 如盘点完，则将盘点单更新为已盘完状态，并将盘点库存更新到商品的库存字段
			 * ----------------------------------------------------------------------
			 */
			if (checkedOver) {
				vcl.setIsCheckOver(true);
				checklistService.update(vcl);

				for (VChecklistItem vcli : vclis) {
					VGoodsRepertory vg = new VGoodsRepertory();
					vg.setIrid(vcl.getRid());
					String sLong = String.valueOf(vcli.getCheckAmount()); 
					vg.setNum(Integer.parseInt(sLong));
					vg.setGid(vcli.getGid());
					goodsreService.updateCheck(vg);
//					VGoods paramg = new VGoods();
//					paramg.setId(vcli.getGid());
//					List<VGoods> vgoods = goodsService.combobox(paramg);
//					VGoods vg = vgoods.get(0);
//					String sLong = String.valueOf(vcli.getCheckAmount());
//					vg.setAmount(Integer.parseInt(sLong));
//					goodsService.update(vg);
					
				}
			}
			j.setSuccess(true);
			j.setMsg("编辑成功！");
		} catch (Exception e) {
			logger.error(ExceptionUtil.getExceptionMessage(e));
			j.setMsg("编辑失败！");
		}
		super.writeJson(j);
	}

	/**
	 * 删除盘点单
	 * 
	 */
	public void delete() {
		Json j = new Json();
		checklistService.delete(model.getIds());
		j.setSuccess(true);
		j.setMsg("删除成功!");
		super.writeJson(j);
	}

	/**
	 * 重盘库存
	 */
	public void reset() {
		Json j = new Json();
		checklistService.reset(model);
		VChecklistItem vcli = new VChecklistItem();
		vcli.setClid(model.getId());
		checklistItemService.reset(vcli);
		j.setSuccess(true);
		j.setMsg("重盘成功!");
		super.writeJson(j);
	}

	@Override
	public VChecklist getModel() {
		return model;
	}

	public String getItems() {
		return items;
	}

	public void setItems(String items) {
		this.items = items;
	}

}
